import { Router } from "express";
const redis = require("redis");
const redis_cofnig = {
  host: "127.0.0.1",
  port: 6379,
  db: 2
};
const redis_client = redis.createClient(redis_cofnig);
const { promisify } = require("util");
const get = promisify(redis_client.get).bind(redis_client);
const set = promisify(redis_client.set).bind(redis_client);

const router = Router();

router.post("/UpdateClientIP", async function(req, res) {
  try {
    if (!req.body.IP) {
      res.json({ IsSuccess: false, ErrorMsg: `缺少IP参数` });
      return;
    }
    // 设置x点y分z秒过期
    let now = new Date();
    let nowtime = now.getTime();
    let endtime = nowtime + 30000;
    let theEndTime = (endtime - nowtime) / 1000;
    await set(
      `client_ip_${req.body.IP}`,
      req.body.IP,
      'EX',
      // 设置过期时间，单位秒。
      theEndTime
      // 10
    );
    res.json({ IsSuccess: true, Data: null, ErrorMsg: "" });
  } catch (e) {
    res.json({ IsSuccess: false, ErrorMsg: `${e.message}` });
  }
});

router.post("/CheckClientIP", async function(req, res) {
  try {
    if (!req.body.IP) {
      res.json({ IsSuccess: false, ErrorMsg: `缺少IP参数` });
      return;
    }
    let clientIP = await get(`client_ip_${req.body.IP}`);
    if (clientIP) {
      res.json({ IsSuccess: false, ErrorMsg: 'IP已存在' });
      return;
    }
    res.json({ IsSuccess: true, Data: null, ErrorMsg: '' });
  } catch (e) {
    res.json({ IsSuccess: false, ErrorMsg: `${e.message}` });
  }
});
export default router;
